//
//  RootViewController.m
//  MyLearnJob
//
//  Created by qianfeng on 15-6-27.
//  Copyright (c) 2015年 朱共营. All rights reserved.
//

#import "RootViewController.h"
#import "AFNetworking.h"
#import "AppModel.h"
#import "MyCell.h"
#import "ADView.h"
#import "ParticularsViewController.h"
#import "UIImageView+WebCache.h"
#import "JHRefresh.h"
#import "SearchBarViewController.h"
#import "LeftViewController.h"
#import "PPRevealSideViewController.h"
@interface RootViewController ()<UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate,UISearchBarDelegate>
{
    UITableView *_tableView;
    NSMutableArray *_dataArr;
    UIScrollView *_scrollView;
    UIView *_myView;
    NSString *_headID;
    NSMutableArray *_headData;
    
    AFHTTPRequestOperationManager *_manager;
    NSMutableArray *_imageData;
    NSMutableArray *_nameData;
    UIPageControl *_pageControl;
    
    NSInteger _currentPage;
    BOOL _isRefreshing;
    BOOL _isLoadMoring;
    
   
    
    
}
@property(nonatomic,strong)  NSMutableArray *headData;
@property(nonatomic,copy) NSString *headID;
@property(nonatomic) BOOL isRefreshing;
@property(nonatomic) BOOL isLoadMoring;
@property(nonatomic) NSInteger currentPage;

@property(nonatomic,strong) UIPageControl *pageControl;
@property(nonatomic,strong) NSMutableArray *imageData;
@property(nonatomic,strong) NSMutableArray *nameData;
@property(nonatomic,strong) UIScrollView *scrollView;
@property(nonatomic,strong) UIView *myView;
@property(nonatomic,strong) UITableView *tableView;
@property(nonatomic,strong) NSMutableArray *dataArr;


@end

@implementation RootViewController


- (void)preloadLeft{
    LeftViewController *left=[[LeftViewController alloc] init];
    
    [self.revealSideViewController preloadViewController:left forSide:PPRevealSideDirectionLeft withOffset:_offset];

}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(preloadLeft) object:nil];
    [self performSelector:@selector(preloadLeft) withObject:nil afterDelay:0.3];
    
    _offset=floorf(200);
    
    
    
    
    
    [self creatTableView];
    [self firstDownload];
    [self creatRefreshView];
}
- (void)creatTableView{
    self.automaticallyAdjustsScrollViewInsets=NO;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed: @"barbar"] forBarMetrics:UIBarMetricsDefault];
    self.navigationItem.title=@"学习视频";
    self.headData=[[NSMutableArray alloc] init];
    self.imageData=[[NSMutableArray alloc] init];
    self.nameData=[[NSMutableArray alloc] init];
    self.dataArr=[[NSMutableArray alloc] init];
    self.tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, kScreenSize.width, kScreenSize.height-64) style:UITableViewStylePlain];
    _manager=[AFHTTPRequestOperationManager manager];
    _manager.responseSerializer=[AFHTTPResponseSerializer serializer];
   
    [self.tableView registerNib:[UINib nibWithNibName:@"MyCell" bundle:nil]
         forCellReuseIdentifier:@"MyCell"];
    self.tableView.delegate=self;
    self.tableView.dataSource=self;

    [self searchBarView];
    [self setButton];
    [self.view addSubview:self.tableView];
    
}
- (void)setButton{
    UIBarButtonItem *set=[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed: @"btn_menu_hl"] style:UIBarButtonItemStylePlain target:self action:@selector(setBlick:)];
    self.navigationItem.leftBarButtonItem=PP_AUTORELEASE(set);

}
- (void)setBlick:(UIBarButtonItem *)item{
    LeftViewController *left=[[LeftViewController alloc] init];
    
    [self.revealSideViewController pushViewController:left onDirection:PPRevealSideDirectionLeft withOffset:_offset animated:_animated completion:^{
        PPRSLog(@"ok");
    }];
    
    
//    [self.revealSideViewController pushViewController:left onDirection:PPRevealSideDirectionLeft withOffset:_offset animated:_animated];
    
    
    
  //  [self.navigationController pushViewController:left animated:YES];
}
- (void)searchBarView{
    UIBarButtonItem *seach=[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(searchBlick)];
    self.navigationItem.rightBarButtonItem=seach;
    

}
- (void)searchBlick{
    SearchBarViewController *search=[[SearchBarViewController alloc] init];
    search.myDataArr=self.dataArr;

    [self.navigationController pushViewController:search animated:YES];

}

- (void)firstDownload{
    self.currentPage=1;
    self.isLoadMoring=NO;
    self.isRefreshing=NO;
    
    [self addTaskUrl:kFirstURLDown isRefresh:NO];
    [self downLoadHeadURL:kFirstURLUp];
    
}
- (void)creatScrollView{
   // NSLog(@"%@",self.dataArr);
    UIView *view=[[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenSize.width, 160)];
    self.scrollView=[[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, kScreenSize.width, 160)];
    
    NSLog(@"%@",self.imageData);
    for (NSInteger i=0; i<4; i++) {
      //  NSLog(@"%@",self.nameData[i]);
        UILabel *lable=[[UILabel alloc] init];
        lable.frame=CGRectMake(0, 130, kScreenSize.width, 30);
        lable.backgroundColor=[UIColor grayColor];
        lable.font=[UIFont systemFontOfSize:14];
        UIImageView *imageView=[[UIImageView alloc] initWithFrame:CGRectMake(kScreenSize.width*i, 0, kScreenSize.width, 160)];
        [imageView sd_setImageWithURL:[NSURL URLWithString:self.imageData[i]] placeholderImage:[UIImage imageNamed: @"loading"]];
        imageView.tag=101+i;
        lable.text=self.nameData[i];
        imageView.userInteractionEnabled=YES;
        
        UITapGestureRecognizer *g=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(btnClick:)];
        [imageView addGestureRecognizer:g];

        
        
   //     NSLog(@"%@",lable.text);
        [imageView addSubview:lable];
        [self.scrollView addSubview:imageView];
        
        
        
    }
   
   
    self.scrollView.contentSize=CGSizeMake(kScreenSize.width*self.imageData.count, 160);
    self.scrollView.showsVerticalScrollIndicator=YES;
    self.scrollView.pagingEnabled=YES;
    self.scrollView.delegate=self;
    [view addSubview:self.scrollView];
    
    _pageControl =[[UIPageControl alloc] initWithFrame:CGRectMake(kScreenSize.width*3/4, 160-30, kScreenSize.width/4, 30)];
    _pageControl.numberOfPages=self.imageData.count;
    
    [_pageControl addTarget:self action:@selector(pageControlClick:) forControlEvents:UIControlEventValueChanged];
    
    
    [view addSubview:_pageControl];

     self.tableView.tableHeaderView=view;

}
- (void)btnClick:(UITapGestureRecognizer *)recognizer{
    
    NSInteger index=[(UIGestureRecognizer *)recognizer view].tag;
    NSLog(@"%ld",index);
    switch (index-100) {
        case 1:
        {
            NSLog(@"%@",self.headData[index-101]);
            ParticularsViewController *par=[[ParticularsViewController alloc] init];
            
            par.idd=self.headData[index-101];
            [self.navigationController pushViewController:par animated:NO];
            
        }
            break;
        case 2:
        {
            NSLog(@"%@",self.headData[index-101]);
            ParticularsViewController *par=[[ParticularsViewController alloc] init];
            
            par.idd=self.headData[index-101];
            [self.navigationController pushViewController:par animated:NO];

        }
            break;
        case 3:
            
        {
            NSLog(@"%@",self.headData[index-101]);
            ParticularsViewController *par=[[ParticularsViewController alloc] init];
            
            par.idd=self.headData[index-101];
            [self.navigationController pushViewController:par animated:NO];

        }
            break;
        case 4:
        {
            NSLog(@"%@",self.headData[index-101]);
            ParticularsViewController *par=[[ParticularsViewController alloc] init];
            
            par.idd=self.headData[index-101];
            [self.navigationController pushViewController:par animated:NO];

            
        }
            break;
            
        default:
            break;
    }
//    ParticularsViewController *par=[[ParticularsViewController alloc] init];
//   // par.idd=self.headID;
//    [self.navigationController pushViewController:par animated:YES];
}


- (void)pageControlClick:(UIPageControl *)page{
    [self.scrollView setContentOffset:CGPointMake(self.scrollView.bounds.size.width*page.currentPage, 0) animated:YES];
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    CGPoint offeset=_scrollView.contentOffset;
    _pageControl.currentPage=offeset.x/kScreenSize.width;
    
}

- (void)downLoadHeadURL:(NSString *)url {
    __weak typeof(self)weakSelf=self;
    NSDictionary *dict=@{@"uid":@(0),@"marking":@"banner",@"token":@"8301d54bbde33ffc9cce3317a51ecd13"};
    [_manager POST:url parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
       
        NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSArray *data=dic[@"data"];
        for (NSDictionary *sub in data) {
            NSString *strPic=[[NSString alloc] initWithString: sub[@"pic"]];
            NSString *strName=[[NSString alloc] initWithString:sub[@"name"]];
           
         //   NSString *headid=[[NSString alloc] initWithString:sub[@"id"]];
            [weakSelf.nameData addObject:strName];
            [weakSelf.imageData addObject:strPic];
            [weakSelf.headData addObject:sub[@"type_id"]];
            NSLog(@"%@",sub[@"type_id"]);
            NSLog(@"%@",self.headData);
        }
        [weakSelf creatScrollView];
        
        [weakSelf.tableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示" message:@"请检查网络连接" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
        [alert show];
    }];


}
- (void)addTaskUrl:(NSString *)url isRefresh:(BOOL)isRefresh{
    __weak typeof(self)weakSelf=self;

    
    NSDictionary *dict=@{@"timestamp":@"1435384729488",@"uid":@(0),@"page":@(_currentPage),@"token":@"7f75e24cb1f7e5c358f03a7b40a60976"};
    
   
    
    [_manager POST:url parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (responseObject) {
            
            NSDictionary *dictNew=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            if ([dictNew[@"errorCode" ] isEqual:@(1005)]) {
                NSLog(@"%ld",self.currentPage);
                _currentPage=_currentPage-1;
                NSLog(@"%ld",self.currentPage);
                UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示" message:@"已经到底部了亲" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
                [alert show];
                [self endRefreshing];
                return ;
            }
            NSArray *arr=dictNew[@"data"];
            
            for (NSDictionary *sub in arr) {
                AppModel *model=[[AppModel alloc] init];
                [model setValuesForKeysWithDictionary:sub];
               
                [_dataArr addObject:model];
            }
            [weakSelf.tableView reloadData];
            [weakSelf endRefreshing];
           
            
            
        }
 } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
       NSLog(@"下载失败");
     UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示" message:@"请检查网络连接" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
     [alert show];
 }];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return self.dataArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MyCell *cell=[tableView dequeueReusableCellWithIdentifier:@"MyCell" forIndexPath:indexPath];
    AppModel *model=self.dataArr[indexPath.row];
    [cell showDataWithModel:model];

    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 115;

}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    ParticularsViewController *partic=[[ParticularsViewController alloc] init];
    AppModel *model=self.dataArr[indexPath.row];
    partic.idd=model.id;
    
   // self.navigationController.hidesBarsOnSwipe=YES;
    [self.navigationController pushViewController:partic animated:NO];

}
- (void)creatRefreshView{
    __weak typeof(self)mySelf=self;
    [self.tableView addRefreshHeaderViewWithAniViewClass:[JHRefreshCommonAniView class] beginRefresh:^{
        if (mySelf.isRefreshing) {
            return ;
        }
        mySelf.currentPage=1;
        mySelf.isRefreshing=YES;
        [mySelf addTaskUrl:kFirstURLDown isRefresh:YES];
    }];
    [self.tableView addRefreshFooterViewWithAniViewClass:[JHRefreshCommonAniView class] beginRefresh:^{
        if (mySelf.isLoadMoring) {
            return ;
        }
        mySelf.isLoadMoring=YES;
        mySelf.currentPage++;
        [mySelf addTaskUrl:kFirstURLDown isRefresh:YES];
       // NSLog(@"%ld",self.currentPage);
    }];


}
- (void)endRefreshing{
    if (self.isRefreshing) {
        self.isRefreshing=NO;
        [self.tableView headerEndRefreshingWithResult:JHRefreshResultSuccess];
    }
    if (self.isLoadMoring) {
        self.isLoadMoring=NO;
        [self.tableView footerEndRefreshing];
    }

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
